/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Utilidades;

/**
 *
 * @author Gutto e Cicinho
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;

/**
 *
 * @author Convidado
 */
public class LocaleHelper {

    protected static String carregarMensagemDeArquivo(String chave, Object parameters[]) {
        //código pra carregar e retornar texto da chave do arquivo Mensagens
        FacesContext context = FacesContext.getCurrentInstance();
        Locale myLocale = context.getViewRoot().getLocale();
        String text = getLocaleString(context.getApplication().getMessageBundle(), chave, parameters , myLocale);
        return text;
    }

    protected static ClassLoader getClassLoader(Object defaultObject) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = defaultObject.getClass().getClassLoader();
        }
        return loader;
    }

    public static String getLocaleString(String bundle, String key, Object parameters[], Locale locale) {
        String text = null;
        ResourceBundle resourceBundle = ResourceBundle.getBundle(bundle, locale, getClassLoader(parameters));
        try {
            text = resourceBundle.getString(key);
        } catch (MissingResourceException e) {
            text = "Erro";
        }
        if (parameters != null) {
            StringBuffer stringBuffer = new StringBuffer();
            MessageFormat messageFormat = new MessageFormat(text, locale);
            text = messageFormat.format(parameters, stringBuffer, null).toString();
        }
        return text;
    }
}

